using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Core.Extension;
using Core.Mgr.ABTest;
using Core.Mgr.Localize;
using Logic.Global;
using Model;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;

namespace Core.Mgr
{
    /// <summary>
    /// 管理着所有的配置表
    /// </summary>
    public class ConfigMgr : Singleton<ConfigMgr>
    {
        private int _finishedNum = 0;
        private int _asyncLoadNum = 0;
        public ConfigModel ConfigModel { get; private set; } = new ConfigModel();

        public IEnumerator OnInit()
        {
            // 在这里配置文件的名称和处理配表得回调
            StartLoadRemoteFile("MainConfig.json", ParseMainConfig);
            // StartLoadRemoteFile("MultiLanguage.txt", LocalizeMgr.Ins.OnInit);
            yield return new WaitUntil(() => _finishedNum == _asyncLoadNum);
        }

        private void ParseMainConfig(string obj)
        {
            ConfigModel = JsonConvert.DeserializeObject<ConfigModel>(obj);
            if (ConfigModel != null)
            {
                AbTestMgr.OnInit(ConfigModel);
            }
        }

        void StartLoadRemoteFile(string fileName, Action<string> finishCallback)
        {
            bool loadLocal = Debuger.Ins.loadLocal;
#if !UNITY_EDITOR
            loadLocal = false;
#endif
            _asyncLoadNum++;
            GameRoot.Ins.StartCoroutine(LoadRemoteFile(fileName, loadLocal, finishCallback));
        }

        private IEnumerator LoadRemoteFile(string fileName, bool local,
            Action<string> callback)
        {
            string loadName = fileName;
            string targetUrl = $"{AppConst.AssetServerUrl}/{loadName}";
            if (local)
            {
                targetUrl = $"{Application.streamingAssetsPath}/Local/{loadName}".ToAdaptPlatform();
            }

            string cachePath = AppConst.AssetCachePath($"{AppConst.CurVersion}/" + loadName);
            UnityWebRequest request = UnityWebRequest.Get(targetUrl);
            request.timeout = 2;
            yield return request.SendWebRequest();
            if (request.result == UnityWebRequest.Result.Success)
            {
                string newData = request.downloadHandler.text;
                if (!local)
                    File.WriteAllText(cachePath, newData);
                Debug.Log("load" + targetUrl);
                Debug.Log("Json Data: " + newData);
                callback?.Invoke(newData);
                _finishedNum++;
            }
            else
            {
                if (File.Exists(cachePath))
                {
                    string oldData = File.ReadAllText(cachePath);
                    Debug.Log("load" + cachePath);
                    Debug.Log("Json Data: " + oldData);
                    callback?.Invoke(oldData);
                    _finishedNum++;
                }
                else
                {
                    yield return GameRoot.Ins.StartCoroutine(LoadRemoteFile(fileName, true, callback));
                }
            }
        }
    }
}